import AsyncStorage from "@react-native-community/async-storage";
import { HOST, WS } from "../config/dev";
import { CURRENT_USER_KEY } from "../storage";
import Store from '../store'
import { UPDATE_MESSAGE_LIST } from "../store/reducer/message";
import {MESSAGE_CONTENT_TYPE, MESSAGE_TYPE} from '../types/message'

class Chat{
    static getInstance() {
        if(!this.instance) {
            this.instance = new Chat()
        }
        return this.instance
    }

   async setUp(url) {
    const userStr = await AsyncStorage.getItem(CURRENT_USER_KEY);
    const user = userStr ? JSON.parse(userStr) : null;
    if (!user) {
      return;
    }
    this.userInfo = user;
    this.chatSocket = new WebSocket(WS+url);
    this.chatSocket.onopen = e=> {
        console.log(e, 'open_small')
    }
    this.chatSocket.onmessage = e=> {
      this.reciveMessage(JSON.parse(e.data))
    //    if (data.type === MESSAGE_TYPE.PRIVATE){
    //     this.reciveMessage(data.msgData)
    //    }
    //    if(data.type=== MESSAGE_TYPE.CONFIRM){

    //        this.confirmMessage(data.msgData)
    //    }
    }

    this.chatSocket.onclose = e=> {
        console.log(e, 'open_small')
    }
    this.chatSocket.onerror = e => {
        console.log(e, 'error')
    }
    return { status: true, errmsg: 'ok' };
  }
//  发送消息
  sendMessage (data, toUser,isGroup=false) {
    const rawData = data[0]
    const message = {
      hash: rawData._id,
      uid: rawData.user._id,
      dist_type: isGroup? MESSAGE_TYPE.GROUP : MESSAGE_TYPE.PRIVATE ,
      fid: toUser,
      content_type: MESSAGE_CONTENT_TYPE.TEXT,
      content: rawData.text,
      create_time: rawData.createdAt,
    }

    const record = {
      ...message,
      is_owner: true
    }
    this.chatSocket.send(JSON.stringify(message))
    Store.dispatch({
      type: UPDATE_MESSAGE_LIST,
      payload: {list: [record], isRead: true, currentUserId: this.userInfo.userId }
    })
  }

  close_soket() {
      this.chatSocket.close() 
  }
  // 接受好友的消息
  reciveMessage (data) {

    const message = data.message
    if(message.userId===this.userInfo.userId) {
      return
    }
    if(message) {
        Store.dispatch(
        {
            type: UPDATE_MESSAGE_LIST, 
            payload:{list: [message], currentUserId: this.userInfo.userId}
        }
      )
    }
  }
  confirmMessage(data) {
      console.log('确认收到信息')
  }
}

export default Chat.getInstance()